#include "stdafx.h"
#include "LuaAdapter.h"
#include "LuaASM.h"
#include "LuaMemory.h"
#include "ConsoleDlg.h"

#include<comutil.h>
#include <stdarg.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define LUA_ERR 999;

CLua::CLua()
{
	m_LuaState=NULL;
}


CLua::~CLua()
{
}


void CLua::Init()
{
	m_LuaState=lua_open();
	luaL_openlibs(m_LuaState);
	RegisterEssential();
}

void CLua::UnInit()
{
	if (m_LuaState)
	{
		lua_close(m_LuaState);
	}
	m_LuaState=NULL;
}

bool CLua::RunFile( const char* filePath )
{
	int err=luaL_loadfile(m_LuaState,filePath);
	if (err)
	{
		SetLastError(L"Load File Failed!Error Code:%d",err);
		return false;
	}
	err=lua_resume(m_LuaState,0);
	if (err)
	{
		SetLastError(L"Run File Failed!Error Code:%d",err);
		return false;
	}
	return true;
}

bool CLua::RunScript( char* script )
{
	int error = luaL_loadbuffer(m_LuaState, script, strlen(script), 
		"line") || lua_pcall(m_LuaState, 0, 0, 0); 
	if (error) { 
		_bstr_t a2w(lua_tostring(m_LuaState, -1));
		LastErrorStr=(wchar_t*)a2w; 
		lua_pop(m_LuaState, 1);
		return false;
	}
	return true;
}

std::wstring CLua::GetLastError()
{
	return LastErrorStr;
}

void CLua::SetLastError( const wchar_t* _Format,... )
{
	wchar_t tempstr[50]={0};
	va_list args;
	va_start(args, _Format);
	_vstprintf_s(tempstr, _Format, args);
	va_end(args);
	LastErrorStr=tempstr;
}

bool CLua::RegisterEssential()
{
	OpenLuaASM(m_LuaState);
	OpenLuaMemory(m_LuaState);
	return true;
}

void CLua::SetOutputConsole( CConsoleDlg* dev )
{
	lua_pushstring(m_LuaState,"Console");
	lua_pushlightuserdata(m_LuaState,(void*)dev);
	lua_settable(m_LuaState,LUA_REGISTRYINDEX);
}

bool CLua::ExportFunction( const char* funcName,luaFunction func)
{
	if (!m_LuaState)
	{
		return false;
	}
	lua_register(m_LuaState,funcName,func);
	return true;
}

bool CLua::ExportModule( const char* libName,const luaLib lib)
{
	if (!m_LuaState)
	{
		return false;
	}
	luaI_openlib(m_LuaState,libName,lib,0);
	return true;
}

